package com.ys.web.yinsheng.util;

import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
public class HttpClient {

	private static OkHttpClient client = null;

	public static int DEFAULT_TIME_OUT = 30;

	static {
		client = new OkHttpClient.Builder().connectTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS)
				.writeTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS).readTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS)
				.build();
	}

	/**
	 * post
	 * 
	 * @param httpUrl
	 * @param params
	 * @return
	 */
	public static String post(String httpUrl, Map<String, String> params) {
		try {
			FormBody.Builder formBodyBuilder = new FormBody.Builder();
			for (String key : params.keySet()) {
				formBodyBuilder.add(key, params.get(key));
			}
			Request request = new Request.Builder().url(httpUrl).post(formBodyBuilder.build()).build();
			Response response = client.newCall(request).execute();
			if (!response.isSuccessful()) {
				log.error("请求内部服务器失败: " + response.code());
			}
			return response.body().string();
		} catch (Exception e) {
			e.printStackTrace();
			log.error("调用银盛接口post错误: " , e);
		}
		return null;
	}

}
